/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cdtserver;
import java.io.*; // classes para input e output streams e
import java.net.*;// DatagramaSocket,InetAddress,DatagramaPacket
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.soap.SAAJMetaFactory;
import org.omg.IOP.Encoding;

/**
 *
 * @author Airton
 */
public class UDPClient extends Thread {
// Lê uma linha do teclado
// Envia o pacote (linha digitada) ao servidor
    connectionType connectType;
    int windowsSize;

  public UDPClient() {};
  public UDPClient(connectionType connType, int winSize)
   {
      connectType = connType;
      windowsSize = winSize;
   }

  public void run(){

      //Try 10 times to connect
       while( !tryConnection() ){
            System.out.println("Trying...");
            try {
                sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(UDPClient.class.getName()).log(Level.SEVERE, null, ex);
            }
          }

       //If connected
       System.out.println("Connected!");
      }


  private void parseStrByte(String text, int size, byte[] data, int posOffset){
      int txtSize = text.length();

      for(int pos = posOffset; pos <= txtSize-1; pos++){
        data[pos] = (byte) text.charAt(pos);
      }

      //data = text.substring(posOffset, txtSize-1).getBytes();

      int left = size - txtSize;
      for(int i=txtSize-1; i<= left; i++)
          data[i] = Byte.parseByte("0");

  }

  public boolean tryConnection(){
      //envia packet com request de connection
      byte[] msgData = new byte[128];
      
      //parseStrByte("localhost", 10, msgData, 0);
      //parseStrByte("localhost", 10, msgData,10);
      byte[] temp = "localhost localhost ".getBytes();
      System.arraycopy(temp,0, msgData, 0, 20);
      msgData[20] = (byte)  connectType.requestConnection.ordinal();
      msgData[21] = Byte.parseByte("0");
      
      Message msgRequest = new Message(msgData, 128);

      return sendPacket(msgRequest);
  }

    
    public boolean sendPacket(Message msg) {
        System.out.println("Client try connection... ");
      // cria o stream do teclado
    //  BufferedReader inFromUser =
    //     new BufferedReader(new InputStreamReader
     //                (System.in));

      // declara socket cliente
      DatagramSocket clientSocket = null;
        try{
            clientSocket = new DatagramSocket();
        } catch (SocketException ex) {
            Logger.getLogger(UDPClient.class.getName()).log(Level.SEVERE, null, ex);
        }

      // obtem endereço IP do servidor com o DNS
      InetAddress IPAddress = null;
        try {
            IPAddress = InetAddress.getByName("localhost");
        } catch (UnknownHostException ex) {
            Logger.getLogger(UDPClient.class.getName()).log(Level.SEVERE, null, ex);
        }

      byte[] sendData = null;
      byte[] receiveData = new byte[1024];

      // retira stream bytes da msg para enviar
      
      sendData = msg.getData();

      // cria pacote com o dado, o endereço do server e porta do servidor
      DatagramPacket sendPacket =
         new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
        try {
            //envia o pacote
            clientSocket.send(sendPacket);
        } catch (IOException ex) {
            Logger.getLogger(UDPClient.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            // fecha o cliente
            clientSocket.close();
            return true;
        }
      
    }
}
